// pages/reservation/list.js
const app = getApp()
import api from '../../utils/api'
import auth from '../../utils/auth'

const STATUS_TEXT_MAP = {
  pending: { text: '待审核', cls: 'pending' },
  approved: { text: '已确认', cls: 'confirmed' },
  rejected: { text: '已拒绝', cls: 'rejected' },
  cancelled: { text: '已取消', cls: 'canceled' }
}

Page({
  data: {
    loading: false,
    refreshing: false,
    list: [],
    page: 1,
    limit: 10,
    total: 0,
    pages: 0,
    status: '', // '', '0','1','2','3'
    hasMore: true
  },

  onLoad() {
    this.init()
  },

  async init() {
    const hasToken = !!(app.globalData.token || wx.getStorageSync('token'))
    if (!hasToken) {
      await auth.requireLogin()
    }
    this.resetAndLoad()
  },

  resetAndLoad() {
    this.setData({ page: 1, list: [], hasMore: true })
    this.loadList()
  },

  async loadList() {
    if (this.data.loading || !this.data.hasMore) return
    this.setData({ loading: true })
    try {
      const params = { page: this.data.page, limit: this.data.limit }
      if (this.data.status !== '' && this.data.status !== undefined) {
        params.status = this.data.status
      }
      const data = await api.reservation.getTeamList(params)
      const list = (data.list || []).map(item => {
        const map = STATUS_TEXT_MAP[item.status] || { text: item.status, cls: 'pending' }
        return { ...item, statusText: map.text, statusClass: map.cls }
      })
      const pagination = data.pagination || { total: 0, pages: 1 }
      const merged = [...this.data.list, ...list]
      this.setData({
        list: merged,
        total: pagination.total || merged.length,
        pages: pagination.pages || 1,
        hasMore: this.data.page < (pagination.pages || 1)
      })
    } catch (e) {
      wx.showToast({ title: e.message || '加载失败', icon: 'none' })
    } finally {
      this.setData({ loading: false, refreshing: false })
    }
  },

  onPullDownRefresh() {
    this.setData({ refreshing: true })
    this.resetAndLoad()
    wx.stopPullDownRefresh()
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({ page: this.data.page + 1 })
      this.loadList()
    }
  },

  // 顶部分类切换
  async navigateCategory(e) {
    const type = e.currentTarget.dataset.type
    if (type === 'personal') {
      const ok = await app.checkAuth()
      if (!ok) return
      wx.navigateTo({ url: '/pages/profile/reservations' })
    } else if (type === 'activity') {
      const ok = await app.checkAuth()
      if (!ok) return
      wx.navigateTo({ url: '/pages/profile/activities' })
    } else {
      // 当前页 team
    }
  },

  changeStatus(e) {
    const status = e.currentTarget.dataset.status
    this.setData({ status: status === undefined ? '' : status, page: 1, list: [], hasMore: true })
    this.loadList()
  },

  async cancelTeam(e) {
    const id = e.currentTarget.dataset.id
    const canCancel = e.currentTarget.dataset.cancancel
    if (!canCancel) {
      wx.showToast({ title: '不可取消', icon: 'none' })
      return
    }
    const ok = await this.confirmAsync('确定取消该团队预约吗？')
    if (!ok) return
    try {
      await api.reservation.cancelTeam(id)
      wx.showToast({ title: '已取消', icon: 'success' })
      this.resetAndLoad()
    } catch (e) {
      wx.showToast({ title: e.message || '取消失败', icon: 'none' })
    }
  },

  confirmAsync(msg) {
    return new Promise(resolve => {
      wx.showModal({
        title: '提示',
        content: msg,
        success: (res) => resolve(res.confirm),
        fail: () => resolve(false)
      })
    })
  }
})